package com.seagox.desk.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.SecretKey;

public class JwtTokenUtils {
	
	/**
     * 过期时间(单位：ms)
     */
	public static final long EXPIRATION = 86400 * 1000;
	
	public static final String TOKENHEAD = "Bearer ";
	
	private static SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode("MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE59EZZPdnFdCekCtK8YIV85zcFe4WC8FoGe6spZsfUe1uD7h8WUh476bQaClxCk4jZW49PDd72gp6CXQpmYHpzw=="));

	public static String sign(Map<String, Object> payload, long expiration) {
		Date now = new Date(System.currentTimeMillis());
		return Jwts.builder().claims(payload).expiration(new Date(now.getTime() + expiration)).signWith(key).compact();
	}

	public static Map<String, Object> unSign(String token) {
		Map<String, Object> result = new HashMap<>();
		try {
			Jws<Claims> claimsJws = Jwts.parser().verifyWith(key).build().parseSignedClaims(token.replace(TOKENHEAD, ""));
			Claims payload = claimsJws.getPayload();
			result.put("userId", payload.get("userId"));
			result.put("verify", true);
		} catch (Exception e) {
			result.put("verify", false);
			e.printStackTrace();
		}
		return result;
	}

}
